package com.crr;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class ConsumerOne {
    public static void main(String[] args) throws IOException, TimeoutException {
        //创建连接工厂 创建连接
        ConnectionFactory factory = new ConnectionFactory();
        factory.setVirtualHost("/");
        factory.setPort(5672);
        factory.setUsername("user");
        factory.setPassword("chen1116.");
        // factory.setHost("127.0.0.1");

        //创建连接
        Connection conn=factory.newConnection();
        //创建信道
        Channel channel=conn.createChannel();
        //声明队列
        String queueName="work";
        channel.queueDeclare(queueName,false,false, false,null);
        System.out.println("消费者One正在等待处理消息---");
        //消费者消费消息
        channel.basicConsume(queueName,true,(consumerTag,message )->{
            System.out.println("consumerTag>>>"+consumerTag);
            String msg=new String(message.getBody());
            System.out.println("消费者One正在处理消息:"+msg);
            doWork(msg);
        },consumerTag->{});

        //注意 不用关闭释放资源   如果队列中有消息 会消费  没有会阻塞 等待消费
    }
    static void doWork(String msg){
        byte[] tem=msg.getBytes();
        for(int i=0,len=tem.length;i<len;i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
